﻿#include "ssPath.h"
#ifdef SS_USE_WINDOWS
#include <io.h>
#include <direct.h>
#else
#include <unistd.h>
#include <sys/stat.h>
#endif


namespace StarSeeker
{

std::string ssPath::RemoveFileName(const char* path)
{
	std::string ret;
	std::string dirPath(path);
	for (size_t i = dirPath.size(); i > 0; --i)
	{
		if (dirPath[i] == '/' || dirPath[i] == '\\')
		{
			ret = dirPath.substr(0,i);
			break;
		}
	}
	return ret;
}

std::string ssPath::RemoveExtName(const char* path)
{
	std::string ret;
	std::string dirPath(path);
	for (size_t i = dirPath.size(); i > 0; --i)
	{
		if (dirPath[i] == '.')
		{
			ret = dirPath.substr(0,i);
			break;
		}
	}
	return ret;
}

std::string ssPath::ExtName(const char* path)
{
	std::string ret;
	std::string dirPath(path);
	for (size_t i=dirPath.size(); i>0; --i)
	{
		if (dirPath[i]=='.')
		{
			ret = dirPath.substr(i, dirPath.size() - i);
			break;
		}
	}
	return ret;
}

std::string ssPath::BaseName(const char* path, bool ext)
{
	std::string ret;
	std::string dirPath(path);
	for (size_t i = dirPath.size(); i > 0; --i)
	{
		if (dirPath[i] == '/' || dirPath[i] == '\\')
		{
			ret = dirPath.substr(i+1, dirPath.size() - i-1);
			break;
		}
	}
	if (!ext && !ret.empty())
	{
		for (size_t i = ret.size(); i > 0; --i)
		{
			if (ret[i] == '.')
			{
				ret = ret.substr(0,i);
				break;
			}
		}
	}
	return ret;
}

bool ssPath::IsDirExist(const char* path)
{
#ifdef SS_USE_WINDOWS
	return ::_access(path, 0) != -1;
#else
	return ::access(path, 0) != -1;
#endif
}

bool ssPath::MakeDir(const char* path)
{
	std::string dirPath(path);
	if (dirPath.size() >= 1024)
		return false;

	if (dirPath[dirPath.size()-1]!='/' && dirPath[dirPath.size() - 1] != '\\')
	{
		dirPath += '/';
	}

	char tmpDirPath[1024] = {};
	for (size_t i = 0; i<dirPath.size() && i<1024; i++)
	{
		tmpDirPath[i] = dirPath[i];
		if (tmpDirPath[i] == '/' || tmpDirPath[i] == '\\')
		{
#ifdef SS_USE_WINDOWS
			if (::_access(tmpDirPath, 0) == -1)
			{
				int ret = ::_mkdir(tmpDirPath);
#else
			if (::access(tmpDirPath, 0) == -1)
			{
				int ret = ::mkdir(tmpDirPath, S_IRWXU);
#endif
				if (ret == -1)
					return false;
			}
		}
	}
	return true;
}

}
